import * as types from './actionTypes'
import {loginAPI, getTokenInfoAPI} from '../../apis/login'
import {setCookie, removeCookie} from '../../utils/common'

export const updateUserAction = (user) => ({
  type: types.UPDATE_USER,
  user
})

/**
 * 登录
 * @param {*} userName 账号
 * @param {*} password 密码
 */
export const handleLogin = (userName, password) => {
  return async (dispatch) => {
    try {
      const {mobile, name, token, userID, userID2} = await loginAPI(userName, password)
      console.log('用户信息', mobile, name, token, userID, userID2)
      dispatch(updateUserAction({mobile, name, token, userID, userID2}))
      setCookie('token', token)
    } catch (e) {
      throw e
    }
  }
}

/**
 * 通过token获取用户信息
 */
export const getTokenInfo = () => {
  return async dispatch => {
    try {
      const {mobile, name, token, userID, userID2} = await getTokenInfoAPI()
      console.log('用户信息', mobile, name, token, userID, userID2)
      dispatch(updateUserAction({mobile, name, token, userID, userID2}))
      // setCookie('token', token)
    } catch (e) {
      throw e
    }
  }
}

export const logout = () => {
  return dispatch => {
    // 删除token
    removeCookie('token')
    // 清空用户信息
    dispatch(updateUserAction({a: 12}))
  }
}

